/**
 *
 */
package com.feizhi.common.search.index;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.Field.Store;

import com.feizhi.common.hash.MD5;

/**
 * @author shuaqiu
 */
public class LuceneWork {

    private Class<?> entityType;

    private Serializable id;

    private Document document;
    
    private boolean isAddedMetaField;

    public Class<?> getEntityType() {
        return entityType;
    }

    public void setEntityType(final Class<?> entityType) {
        this.entityType = entityType;
    }

    public Serializable getId() {
        return id;
    }

    public void setId(final Serializable id) {
        this.id = id;
    }

    public Document getDocument() {
        if (!isAddedMetaField) {
            addMetaField();
            isAddedMetaField = true;
        }
        return document;
    }

    public void setDocument(final Document document) {
        this.document = document;
    }
    
    private void addMetaField() {
        // add the type meta data.
        final String typeName = entityType.getName();
        final String idStr = id.toString();

        document.add(new StringField(IndexConstants.TYPE_CLASS, typeName, Store.YES));
        document.add(new StringField(IndexConstants.TYPE_ID, idStr, Store.YES));

        try {
            final String key = MD5.md5(typeName + idStr);
            document.add(new StringField(IndexConstants.TYPE_KEY, key, Store.YES));
        } catch (NoSuchAlgorithmException e) {
        }
    }

    @Override
    public String toString() {
        if (document == null) {
            return entityType + "#" + id;
        }
        return entityType + "#" + id +  ":" + document;
    }
}
